import 'package:Sayagh/Configs.dart';
import 'package:Sayagh/i18n/i18nLocale.dart';
import 'package:Sayagh/tablepress/Cities.dart';
import 'package:Sayagh/tablepress/ShowTable.dart';
import 'package:Sayagh/tablepress/csv.dart';
import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';

class DrawerGood {
  int id;
  int isActive;
  String title;
  String fileName;
  String url;
  String description;
  int hasSubTable = 1;
  int hasCategoryColumn = 0;
  int hasCategorySubColumn = 0;

  DrawerGood();

  DrawerGood.fromList(List list) {
    isActive = int.parse(list.removeAt(0));
    title = list.removeAt(0);
    fileName = list.removeAt(0);
    url = list.removeAt(0);
    description = list.removeAt(0);
    hasSubTable = int.parse(list.removeAt(0));
    hasCategoryColumn = int.parse(list.removeAt(0));
    hasCategorySubColumn = int.parse(list.removeAt(0));
  }

  DrawerGood.fromMap(Map map) {
    id = map['id             '.replaceAll(' ', '')];
    isActive = map['isActive             '.replaceAll(' ', '')];
    title = map['title             '.replaceAll(' ', '')];
    fileName = map['fileName           '.replaceAll(' ', '')];
    hasSubTable = map['hasSubTable         '.replaceAll(' ', '')];
    hasCategoryColumn = map['hasCategoryColumn   '.replaceAll(' ', '')];
    hasCategorySubColumn = map['hasCategorySubColumn'.replaceAll(' ', '')];
    url = map['url             '.replaceAll(' ', '')];
    description = map['description         '.replaceAll(' ', '')];
  }

  Map toMap() {
    Map<String, dynamic> map = new Map();
    map['isActive             '.replaceAll(' ', '')] = isActive;
    map['title             '.replaceAll(' ', '')] = title;
    map['fileName           '.replaceAll(' ', '')] = fileName;
    map['hasSubTable         '.replaceAll(' ', '')] = hasSubTable;
    map['hasCategoryColumn   '.replaceAll(' ', '')] = hasCategoryColumn;
    map['hasCategorySubColumn'.replaceAll(' ', '')] = hasCategorySubColumn;
    map['url             '.replaceAll(' ', '')] = url;
    map['description         '.replaceAll(' ', '')] = description;
    return map;
  }
}

class DrawerGoodProvider {
  Database db;

  Future open() async {
    db = await openDatabase(
      ourDatabase,
      version: 1,
      onOpen: (Database db) async {
        String sqlQuery = '''
    CREATE TABLE IF NOT EXISTS "$drawerGoodTable" (
      "id"	INTEGER PRIMARY KEY AUTOINCREMENT,
      "isActive"	INTEGER NOT NULL DEFAULT 1,
      "title"	TEXT NOT NULL UNIQUE,
      "fileName"	TEXT,
      "hasSubTable"	INTEGER NOT NULL DEFAULT 0,
      "hasCategoryColumn"	INTEGER NOT NULL DEFAULT 0,
      "hasCategorySubColumn"	INTEGER NOT NULL DEFAULT 0,
      "url" TEXT default 'http://sayagh.asnafhormozgan.ir',
      "description"	TEXT
    );
  ''';
        await db.execute(sqlQuery);
      },
    );
  }

  Future<DrawerGood> insert(DrawerGood dg) async {
    dg.id = await db.insert("$drawerGoodTable", dg.toMap());
    return dg;
  }

  Future<DrawerGood> getDrawerGood(var code, {bool byTableName = true}) async {
    String column = "fileName";
    if (!byTableName) column = "id";
    List<Map> maps = await db
        .query(drawerGoodTable, where: '$column = ?', whereArgs: [code]);
    if (maps.length > 0) return DrawerGood.fromMap(maps.first);
    return null;
  }

  Future<int> delete(int code, {bool byTableName = true}) async {
    String column = "fileName";
    if (!byTableName) column = "id";
    return await db
        .delete(drawerGoodTable, where: "$column = ?", whereArgs: [code]);
  }

  Future<int> update(DrawerGood dg, {bool byTableName = true}) async {
    String column = byTableName ? "fileName" : "id";
    var whereArg = byTableName ? dg.fileName : dg.id;
    return await db.update(drawerGoodTable, dg.toMap(),
        where: "$column = ?", whereArgs: [whereArg]);
  }

  Future insertOrUpdate(DrawerGood dg, {bool byTableName = true}) async {
    var whereArg = byTableName ? dg.fileName : dg.id;
    final DrawerGood _dg = byTableName
        ? await getDrawerGood(whereArg)
        : await getDrawerGood(whereArg, byTableName: false);
    if (_dg == null) return await insert(dg);
    return byTableName
        ? await update(dg)
        : await update(dg, byTableName: false);
  }

  Future transActionalSaveListOfList(List list) async {
    await db.transaction((txn) async {
      await txn.update(drawerGoodTable, {'isActive': 0}, where: 'id > 0');
      DrawerGood drawerGood;
      for (int i = 0; i < list.length; i++) {
        drawerGood = null;
        if (list[i].length < 8) continue;
        drawerGood = DrawerGood.fromList(list[i]);
        var found = await txn.query(drawerGoodTable,
            where: "fileName = ?", whereArgs: [drawerGood.fileName]);
        if (found.length == 0)
          await txn.insert(drawerGoodTable, drawerGood.toMap());
        else
          await txn.update(drawerGoodTable, drawerGood.toMap(),
              where: "fileName = ?", whereArgs: [drawerGood.fileName]);
      }
    });
  }

  Future<List<DrawerGood>> getAllActive() async {
    await open();
//    print("drawergoodprovide:getAllactive()");
    List<Map> _dg =
        await db.query(drawerGoodTable, where: "isActive > 0", orderBy: "id");
    List<DrawerGood> dg = [];
    _dg.forEach((f) => dg.add(DrawerGood.fromMap(f)));
    return dg;
  }

  Future close() async => db.close();
}

Future updateDrawerGoodsDb() async {
  List<List> dgCSV = await csv(sayaghWebsite, "drawer", "منو", hasSubTable: 1);
  dgCSV = dgCSV[1];
  DrawerGoodProvider drawerGoodProvider = new DrawerGoodProvider();
  await drawerGoodProvider.open();
  await drawerGoodProvider.transActionalSaveListOfList(dgCSV);
}

Future<bool> updateDrawerDb() async {
  await Future.wait([updateDrawerGoodsDb(), updateDrawerCitiesDb()]);
  return true;
}

class DrawerSayagh extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _DrawerSayagh();
  }
}

class _DrawerSayagh extends State<DrawerSayagh> {
  bool _updated = false;
  final DrawerGoodProvider _dgp = new DrawerGoodProvider();
  final CityProvide _cp = new CityProvide();

  @override
  Widget build(BuildContext context) {
    Future<List<DrawerGood>> _drawergoods = _dgp.getAllActive();
    Future<List<City>> _cities = _cp.getAllShouldShow();
    return Drawer(
        child: ListView(
      children: <Widget>[
        ExpansionTile(
          title: Text(
            i18nLocale[ourLocale]["essentials"],
            textDirection: TextDirection.rtl,
            textAlign: TextAlign.center,
            style: TextStyle(fontFamily: "Sahel"),
          ),
          children: <Widget>[
            FutureBuilder(
                future: _drawergoods,
                builder: (BuildContext context, AsyncSnapshot snapshot) {
                  if (snapshot.data == null) {
                    return Text(i18nLocale[ourLocale]["reciving"]);
                  } else {
                    return ListView.builder(
                        shrinkWrap: true,
                        itemCount: snapshot.data.length,
                        itemBuilder: (BuildContext context, int index) {
                          DrawerGood _dg = snapshot.data[index];
                          return ListTile(
                            title: Text(
                              _dg.title,
                              textDirection: TextDirection.rtl,
                            ),
                            onTap: () {
                              csv(_dg.url, _dg.fileName, _dg.title,
                                  isActive: _dg.isActive,
                                  description: _dg.description,
                                  hasSubTable: 0,
                                  hasCategoryColumn: _dg.hasCategoryColumn,
                                  hasSubCategoryColumn:
                                      _dg.hasCategorySubColumn,
                                  updateDate:
                                      new DateTime.now().millisecondsSinceEpoch,
                                  isKala: true,
                                  cityName: "اقلام اساسی");
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => ShowTable(
                                          _dg.title,
                                          _dg.fileName,
                                          hasCategoryColumn:
                                              _dg.hasCategoryColumn,
                                        )),
                              );
                            },
                          );
                        });
                  }
                }),
          ],
          initiallyExpanded: true,
        ),
        ExpansionTile(
          title: Text(
            i18nLocale[ourLocale]["citiesPrices"],
            textDirection: TextDirection.rtl,
            textAlign: TextAlign.center,
            style: TextStyle(fontFamily: "Sahel"),
          ),
          children: <Widget>[
            FutureBuilder(
                future: _cities,
                builder: (BuildContext context, AsyncSnapshot snapshot) {
                  if (snapshot.data == null) {
                    return Text(i18nLocale[ourLocale]["reciving"]);
                  } else {
                    return ListView.builder(
                        shrinkWrap: true,
                        physics: ScrollPhysics(),
                        itemCount: snapshot.data.length,
                        itemBuilder: (BuildContext context, int index) {
                          City _c = snapshot.data[index];
                          return ListTile(
                            title: Text(
                              _c.title,
                              textDirection: TextDirection.rtl,
                            ),
                            onTap: () => Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) => ShowTable(
                                      _c.title, _c.title,
                                      hasCategoryColumn: _c.hasCategoryColumn)),
                            ),
                          );
                        });
                  }
                }),
          ],
        ),
      ],
    ));
  }
}
